package com.example.administrator.readbook.http;

import com.example.administrator.readbook.BuildConfig;
import com.example.administrator.readbook.utils.NetworkUtil;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/7/2.
 */

public class ServiceFactory {

    private volatile static Retrofit requestRetrofitBook;
    private volatile static Retrofit requestRetrofitChapter;
    public static final String BASE_URL_BOOK = "https://api.zhuishushenqi.com/";
    public static final String BASE_URL_CHAPTER = "https://chapter2.zhuishushenqi.com/";

    //默认链接超时时间
    private static final int DEFAULT_TIMEOUT = 20;
    //默认服务器响应时间
    private static final int DEFAULT_READ_TIMEOUT = 20;

    private ServiceFactory() {

    }

    public static OkHttpClient getDefaultClient() {
        // FIXME: 2017/1/22 这里其实只针对GET进行cache，应该自定义缓存

        return new OkHttpClient.Builder()
                .addNetworkInterceptor(getNetWorkInterceptor())
                .addInterceptor(getInterceptor())
                .addNetworkInterceptor(getLoggingInterceptor())
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)
                .build();
    }

    public static HttpLoggingInterceptor getLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
        return loggingInterceptor;
    }

    /**
     * 设置返回数据的  Interceptor  判断网络   没网读取缓存
     */
    public static Interceptor getInterceptor(){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtil.isNetworkAvailable()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                return chain.proceed(request);
            }
        };
    }

    /**
     * 设置连接器  设置缓存
     */
    public static Interceptor getNetWorkInterceptor(){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                if (NetworkUtil.connectionNetwork()) {
                    int maxAge = 0 * 60;
                    // 有网络时 设置缓存超时时间0个小时
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为1周
                    int maxStale = 60 * 60 * 24 * 7;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
    }

    private static Retrofit getDefaultRetrofitBook() {
        if (requestRetrofitBook == null) {
            synchronized (ServiceFactory.class) {
                if (requestRetrofitBook == null) {
                    requestRetrofitBook = new Retrofit.Builder()
                            .baseUrl(BASE_URL_BOOK)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(getDefaultClient())
                            .build();
                }
            }
        }
        return requestRetrofitBook;
    }

    private static Retrofit getDefaultRetrofitChapter() {
        if (requestRetrofitChapter == null) {
            synchronized (ServiceFactory.class) {
                if (requestRetrofitChapter == null) {
                    requestRetrofitChapter = new Retrofit.Builder()
                            .baseUrl(BASE_URL_CHAPTER)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(getDefaultClient())
                            .build();
                }
            }
        }
        return requestRetrofitChapter;
    }

    //处理线程调度的变换
    public static ObservableTransformer schedulersTransformer = new ObservableTransformer() {
        @Override
        public ObservableSource apply(Observable upstream) {
            return ((Observable) upstream).subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    };

    public static ServiceUrl getServiceBook() {
        return getDefaultRetrofitBook().create(ServiceUrl.class);
    }

    public static ServiceUrl getServiceChapter() {
        return getDefaultRetrofitChapter().create(ServiceUrl.class);
    }
}
